from . import admin
from flask import render_template,jsonify,request,url_for
from app.models import Model
import time,random,datetime
from app import app

#首页
@admin.route("/")
def index():
	return render_template('index.html')

#图书列表
@admin.route('/books/index')
def books_index():
	#获取当前所有的图书信息
	#实例化模型对象
	data=Model().query('select * from books')
	print(data)
	return render_template('books/index.html',books=data)

#添加图书
@admin.route('/books/add',methods=['GET','POST'])
def books_add():
	#判断请求方式
	if request.method=='GET':
		#显示表业页
		return render_template('books/add.html')
	else:
		#处理表单页
		data=request.form.to_dict()


		#判断是否上传了封面图片
		myfile=request.files.get('pic')
		if myfile:
			# 执行文件的上传操作
			Suffix = myfile.filename.split('.').pop()  # 1.jpg
			filename = str(time.time()) + str(random.randint(10000, 99999)) + '.' + Suffix
			myfile.save(app.config["UP_DIR"] + filename)
			data['pic_url'] = filename

		data['addtime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
		print(data)
		# 执行数据的添加
		sql = '''insert into books(id,title,author,pic_url,price,publisher,isbn13,summary,catalog,pubdate,author_intro,status,num,addtime) values(
		       null,"{title}","{author}","{pic_url}"
		       ,"{price}","{publisher}","{isbn13}","{summary}"
		       ,"{catalog}","{pubdate}","{author_intro}"
		       ,"{status}","{num}","{addtime}"
		       )
		       '''.format(id='null',title=data['title'],author=data['author'],pic_url=data['pic_url'],price=data['price'],publisher=data['publisher'],isbn13=data['isbn13'],summary=data['summary'],catalog=data['catalog'],pubdate=data['pubdate'],author_intro=data['author_intro'],status=data['status'],num=data['num'],addtime=data['addtime'])
		res = Model().exec(sql)
		print(sql)
		if res:
			return '<script>alert("添加成功");location.href="' + url_for('admin.books_index') + '"</script>'

		return '<script>alert("添加失败");location.href="' + url_for('admin.books_add') + '"</script>'

@admin.route('/books/serach',methods=['GET','POST'])
def books_serach():
	id=request.args.get('id')
	#print(id)
	import requests
	import json
	import codecs
	import datetime
	url = 'https://douban.uieee.com/v2/book/isbn/'+id
	# 参数列表
	start = 0
	count = 0
	r = requests.get(url, params={'start': start, 'count': count})
	r.encoding = 'UTF_8'
	content = r.json()
	res = dict(content)
	database = {}
	database['id'] = 'null'
	database['title'] = res['title']
	database['author'] = res['author']
	database['price'] = res['price']
	database['publisher'] = res['publisher']
	database['isbn13'] = res['isbn13']
	database['summary'] = res['summary']
	database['catalog'] = res['catalog']
	database['pubdate'] = res['pubdate']
	database['author_intro'] = res['author_intro']
	database['status'] = 0
	database['num'] = 1
	database['addtime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
	database['pic_url'] = res['images']['small']

	data=database
	# for i, k in database.items():
	# 	print(i, k)
	sql = '''insert into books(id,title,author,pic_url,price,publisher,isbn13,summary,catalog,pubdate,author_intro,status,num,addtime) values(
			       null,"{title}","{author}","{pic_url}"
			       ,"{price}","{publisher}","{isbn13}","{summary}"
			       ,"{catalog}","{pubdate}","{author_intro}"
			       ,"{status}","{num}","{addtime}"
			       )
			       '''.format(id='null', title=data['title'], author=data['author'], pic_url=data['pic_url'],
							  price=data['price'], publisher=data['publisher'], isbn13=data['isbn13'],
							  summary=data['summary'], catalog=data['catalog'], pubdate=data['pubdate'],
							  author_intro=data['author_intro'], status=data['status'], num=data['num'],
							  addtime=data['addtime'])
	res = Model().exec(sql)

	return '入库成功'